<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 小动作函数库
 * 
 * @desc	处理简单的小动作：收藏，关注，赞顶踩等的业务处理流程
 * @version 1.0.0 
 * @author  Jason
 * @date	2017年7月11日 下午1:57:05
 */
class Lib_trick extends Lib_database
{
	/** @var Mod_trick */
	private $mod_trick = null;
	
	use libraries\common\DatabaseCURD;
	
	use libraries\common\ConditionParser;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->CI->config->load('enumeration');
		
		$this->CI->load->model('mod_trick');
		$this->mod_trick =& $this->CI->mod_trick;
		
		$this->set_render_config();
	}
	
	private function set_render_config()
	{
		$foreign_keys = [
				'master' => [
						['source_id', ['name'], $this->CI->mod_member, 'master', 'id'],
						['source_id', ['nickname'], $this->CI->mod_member, 'info', 'id'],
				],
		];
		$time_fields = [
				'master' => [
						['create_time', 'Y-m-d H:i:s'],
				],
		];
		$encode_fields = [
				'master' => [
				],
		];
		$this->foreign_keys = $foreign_keys;
		$this->time_fields = $time_fields;
		$this->encode_fields = $encode_fields;
	}
	
	public function get_trick_detail($id)
	{
		$item = $this->mod_trick->select_instance_by_id($id);
		$item = $this->render_list($item, 'master', true, [
				[$this, 'parse_trick_item'],
		]);
		return $item;
	}
	
	/**
	 * 获取小动作列表
	 * 
	 * @desc    直取数据库记录
	 * @author  Jason
	 * @date	2017年7月7日 下午3:46:09
	 * 
	 * @param   
	 * 
	 * @return  array
	 */
	public function get_tricks_list($conditions, $page = 1, $number = 12)
	{
		$data = $this->mod_trick->get_list($conditions, $page, $number);
		$data['data'] = $this->render_list($data['data'], 'master', false, [
				[$this, 'parse_trick_item'],
		]);
		return $data;
	}
	
	/**
	 * 随意限定条件(类型+id)查询获取小动作列表
	 *
	 * @desc    按小动作类型和源资源类型，获取特定（指定）目标类型的小动作目标ID列表
	 * @author  Jason
	 * @date	2017年7月12日 下午3:09:15
	 *
	 * @param
	 * 
	 * @version	1.1.0
	 * @desc	一行随意限定条件的查询
	 * @author	Jason
	 * @date	2017年7月17日 下午8:39:34
	 *
	 * @return  array
	 */
	public function get_tricks_list_by_somekey($conditions, $page = 1, $number = 12, $type = null, $source_type = null, $source_id = null, $target_type = null, $target_id = null)
	{
		$key = [];
		is_null($type) 			OR $key['type'] = $type;
		is_null($source_type) 	OR $key['source_type'] = $source_type;
		is_null($source_id) 	OR $key['source_id'] = $source_id;
		is_null($target_type) 	OR $key['target_type'] = $target_type;
		is_null($target_id) 	OR $key['target_id'] = $target_id;
		empty($key) OR array_push($conditions, ['where', [$key]]);
		$data = $this->get_tricks_list($conditions, $page, $number);
		return $data;
	}
	
	public function parse_trick_item($item)
	{
		$mapper_metrix = $this->CI->config->item('mapper_metrix')['trick']['master'];
		
		$item['type_text'] = @$mapper_metrix['type'][$item['type']];
		$item['source_type_text'] = @$mapper_metrix['source_type'][$item['source_type']];
		$item['target_type_text'] = @$mapper_metrix['target_type'][$item['target_type']];
		
		return $item;
	}
	
	/**
	 * if in controller, it must be public , or is_callable($callback) -> false!
	 * but if public in controller, is should be an Action Entry! REALLY TOO BAD!!
	 * @param array $item
	 */
	public function parse_trick_touroute_item($item)
	{
		$this->CI->load->library('lib_touroute');
		$cookie_lang = $this->CI->lib_cookie->get_language();
		$language = $this->CI->lib_language->get_supported_language($this->CI->language, $cookie_lang);
		$currency = $this->CI->lib_cookie->get_currency();
		
		$currency = strtolower($currency);
		$item['target_id_current_currency'] = strtoupper($currency);
		$item['target_id_retail_current'] = $item["target_id_retail_$currency"];
		
		$module = 'area';
		$resources = array($item['target_id_country'], $item['target_id_city']);
		$item['target_id_address_string'] = sprintf('%s %s %s',
				$this->CI->lib_language->get_concat_values_string_by_language($module, $resources, $language),
				@$item['target_id_street'],
				@$item['target_id_address']
		);
		$item['target_id_direction_url'] = sprintf("https://www.google.com/maps/dir/current+location/%s,%s", $item['target_id_latitude'], $item['target_id_longitude']);
		
		$item['status'] = $item['target_id_status'];
		$item = $this->CI->lib_touroute->parse_item_status($item);
		$item['touroute_status_tags'] = $item['status_tags'];
		
		return $item;
	}
	
	public function render_trick_touroute_list($list)
	{
		$this->CI->load->model('mod_touroute');
		$config = new StdClass();
		$config->foreign_keys = [
				['target_id', ['name', 'cover', 'country', 'city', 'latitude', 'longitude', 'duration',
						'settle_currency', 'settle_amount', 'channel_currency', 'channel_amount',
						'retail_cny', 'retail_usd', 'retail_eur', 'status'
				], $this->CI->mod_touroute, 'master', 'id'],
		];
		$config->time_fields = [
				['create_time', 'Y-m-d H:i:s'],
		];
		$config->encode_fields = [
		];
		$list = $this->render_list($list, $config, false, [
				[$this, 'parse_trick_touroute_item'],
		]);
		
		return $list;
	}
	
	public function parse_trick_merchant_item($item)
	{
		$this->CI->load->library('lib_merchant');
		$cookie_lang = $this->CI->lib_cookie->get_language();
		$language = $this->CI->lib_language->get_supported_language($this->CI->language, $cookie_lang);
		
		$module = 'area';
		$resources = array($item['target_id_country'], $item['target_id_city']);
		$item['target_id_address_string'] = sprintf('%s %s %s',
				$this->CI->lib_language->get_concat_values_string_by_language($module, $resources, $language),
				@$item['target_id_street'],
				@$item['target_id_address']
		);
		$item['target_id_direction_url'] = sprintf("https://www.google.com/maps/dir/current+location/%s,%s", $item['target_id_latitude'], $item['target_id_longitude']);
		
		// FIXME 获取前两个路线的图片和名称信息
		$this->CI->load->library('lib_touroute');
		$this->CI->load->model('mod_touroute');
		$status_tags = ['check_over', 'checked', 'enabled'];
		$where =  $this->CI->mod_touroute->calculate_status_condition_where($status_tags);
		$conditions[] = ['select', 'id,name,cover'];
		$conditions[] = ['where', "merchant_id={$item['target_id']}"];
		$conditions[] = ['where', $where];
		$result = $this->CI->mod_touroute->get_list($conditions, 1, 2);
		$module = $this->CI->mod_touroute->get_multi_language_info('module');
		$field_names = ['name'];
		$item['target_id_touroutes'] = $this->CI->lib_language->get_merged_list_data_with_fields($result['data'], $module, $language, $field_names);
		
		return $item;
	}
	
	public function render_trick_merchant_list($list)
	{
		$this->CI->load->model('mod_merchant');
		$config = new StdClass();
		$config->foreign_keys = [
				['target_id', ['name', 'cover', 'mobile', 'email', 'website', 'zipcode', 
						'is_official', 'country', 'city', 'street', 'address', 'latitude', 'longitude',
						'status'
				], $this->CI->mod_merchant, 'master', 'id'],
		];
		$config->time_fields = [
				['create_time', 'Y-m-d H:i:s'],
		];
		$config->encode_fields = [
		];
		$list = $this->render_list($list, $config, false, [
				[$this, 'parse_trick_merchant_item'],
		]);
		
		return $list;
	}
	
	
	
	/**
	 * 是否是支持的枚举值
	 *
	 * @date	2017年7月6日 下午6:39:44
	 *
	 * @param string $enum	枚举值
	 * @param string $field	枚举类型
	 *
	 * @return boolean
	 */
	private function is_supported_enum_in_field($enum, $field)
	{
		$mapper_metrix = $this->CI->config->item('mapper_metrix')['trick']['master'];
		return array_key_exists($enum, $mapper_metrix[$field]);
	}
	public function is_supported_type($enum)
	{
		$field = str_replace('is_supported_', '', __FUNCTION__);
		return $this->is_supported_enum_in_field($enum, $field);
	}
	public function is_supported_source_type($enum)
	{
		$field = str_replace('is_supported_', '', __FUNCTION__);
		return $this->is_supported_enum_in_field($enum, $field);
	}
	public function is_supported_target_type($enum)
	{
		$field = str_replace('is_supported_', '', __FUNCTION__);
		return $this->is_supported_enum_in_field($enum, $field);
	}
	
	
	/**
	 * 小动作添加和删除切换
	 * 
	 * @desc    如果存在对应复合主键的数据，删除之；否则添加。
	 * @author  Jason
	 * @date    2017年7月11日 下午4:25:47
	 * 
	 * @param   $type, $source_type, $source_id, $target_type, $target_id, $content
	 *
	 * @return  [<status>, <content>]	一个两元素数组，第一个元素表示状态，第二个表示相应内容
	 * 	        eg:	[true, <userData>]
	 * 				[false, <errorMesg>]
	 */
	public function toggle_create_delete()
	{
		$this->CI->load->library('form_validation');
		
		$status = false;
		$content = [];
		if(FALSE === $this->CI->form_validation->run("trick_create")) {
			$errorKey = $this->CI->form_validation->error_array();
			$status = false;
			$content = $errorKey;
		} else {
			$data = $this->CI->input->post();
			
			$conditions = [
					['select', 'id'],
					['where', [[
							'type' => $data['type'],
							'source_type' => $data['source_type'],
							'source_id' => $data['source_id'],
							'target_type' => $data['target_type'],
							'target_id' => $data['target_id'],
					]]],
			];
			$has = $this->mod_trick->select_instance_by_conditions($conditions);
			if ($has) {
				$this->mod_trick->delete_instance_by_id($has['id']);
				$status = true;
				$content = ['oper' => 'delete' , 'nowStatus' => 'Cancelled'];
			} else {
				list($status, $content) = $this->mod_trick->create_instance($data);
				if ($status) {
					$content = ['oper' => 'create' , 'nowStatus' => 'Confirmed', 'insertId' => $content['id']];
				} else {
					$content = ['common_msg_create_faild'];
				}
			}
		}
		
		return [$status, $content];
	}
	
	/**
	 * 操作前所有权验证
	 *
	 * @desc	摘自 toggle_shelve 方法
	 * @author  Jason
	 * @date	2017年5月25日 下午3:54:36
	 *
	 * @param number $id
	 * @param number $member_id
	 *
	 * @return  [<status>, <content>]	一个两元素数组，第一个元素表示状态，第二个表示相应内容
	 * 	        eg:	[true, <userData>]
	 * 				[false, <errorMesg>]
	 */
	public function before_manage_validation($id, $member_id)
	{
		$status = false;
		$item = $this->mod_trick->select_fields_by_id($id, ['id', 'source_type', 'source_id']);
		
		if (empty($item)) {
			// Trick Notfound
			return [$status, ['trick_msg_trick_notfound']];
		}
		
		if ($item['source_id'] != $member_id) {
			// no authority
			return [$status, ['trick_msg_no_authority']];
		}
		
		$status = true;
		return [$status, $item];
	}
	
}